package com.config;


import com.annotation.Lock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁的切面
 */
@SuppressWarnings("ALL")
@Configuration
@Aspect
public class LockAopConfig {

    @Autowired
    private RedissonClient redissonClient;


    //@Around("execution(* com.service.*.*(..))")
    @Around("@annotation(lock)")
    public Object handler(ProceedingJoinPoint joinPoint, Lock lock) throws Throwable {
        String name = lock.name();
        long  waitTime = lock.waitTime();
        long  releaseTime = lock.releaseTime();
        RLock  rLock = redissonClient.getLock(name);
        boolean  f   = rLock.tryLock(waitTime,releaseTime, TimeUnit.MILLISECONDS);
        if (f) //获取到锁
        {
            Object obj = joinPoint.proceed();
            Thread.sleep(waitTime+3000);
            return obj;
        }
        return null;

    }

}